package cn.ztuo.bitrade.service;

import cn.ztuo.bitrade.dao.RelationDao;
import cn.ztuo.bitrade.entity.Cesspit;
import cn.ztuo.bitrade.entity.CesspitRecord;
import cn.ztuo.bitrade.entity.Relation;
import cn.ztuo.bitrade.service.Base.BaseService;
import cn.ztuo.bitrade.util.BigDecimalUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Slf4j
@Service
public class RelationService extends BaseService {

    @Autowired
    private RelationDao relationDao;

    @Autowired
    private CesspitRecordService cesspitRecordService;

    @Autowired
    private CesspitService cesspitService;

    private static int DEFAULT_DIV_SCALE = 4;
    /**
     * 判断用户是否已经安置
     * 如果用户已经存说明用户已经安置激活
     * @param uid
     * @return
     */
    public Boolean findActivation(Long uid){
        Boolean isSuccess  = false;
        Relation relation = relationDao.findByUid(uid);
        if(relation != null) isSuccess = true;
        return isSuccess;
    }

    /**
     * 判断用户的左右区是否已经被占用
     * 如果被占用返回TRUE，否则false
     * @param uid 用户的ID
     * @param position 1=左区 2=右区
     * @return
     */
    public Boolean checkPosition(Long uid,int position){
        Boolean isSuccess  = false;
        Relation relation = relationDao.findByPidAndPosition(uid,position);
        if(relation != null) isSuccess = true;
        return isSuccess;
    }

    /**
     * 获取当前用户的安置信息
     * @param uid
     * @return
     */
    public Relation findOneInfo(Long uid){
        return relationDao.findByUid(uid);
    }

    /**
     * 存储用户的安置关系返回成功的ID
     * @param relation
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public Long save(Relation relation){
        Relation data =  relationDao.save(relation);
        return data.getId();
    }

    /**
     * 获取当前用户左右节点信息
     * @param uid
     * @return
     */
    public List<Relation> findByPid(Long uid){
        List<Relation> relation = relationDao.findByPid(uid);
        return relation;
    }

    /**
     * 获取当前用户的左右区的信息
     * @param uid  用户的ID
     * @param position 1||2
     * @return
     */
    public Relation checkPosition2(Long uid,int position){
        return relationDao.findByPidAndPosition(uid,position);
    }

    /**
     * 把用户的左右区信息封装成HASHMAP返回
     * @return
     */
    public HashMap idInfo(Long uid){
        HashMap<String, String> map = new HashMap<>();
        Relation left = relationDao.findByPidAndPosition(uid,1);
        Relation right = relationDao.findByPidAndPosition(uid,2);
        String leftUsername =left==null ? null:left.getUsername();
        String rightUsername =right==null ? null:right.getUsername();
        map.put("leftUsername",leftUsername);
        map.put("rightUsername",rightUsername);
        return map;
    }

    /**
     * 获取当前用户的左区或者右区 IDS列表
     * @param uid
     * @param position
     * @return
     */
    public List<Long> getIds(Long uid,int position){
        List<Long> list = new ArrayList<>();
        Relation Relation = relationDao.findByPidAndPosition(uid,position);
        if(Relation==null) return null;
        List<Relation>  checks = relationDao.findByParentLike("%|"+Relation.getUid()+"|%");
        list.add(Relation.getUid());
        checks.forEach(relation -> list.add(relation.getUid()));
        return list;
    }

    /**
     * 获取当前ID的社区节点个数
     * @param id
     * @return
     */
    public int childs(Long id){
        List<Long> childL = this.getIds(id,1);
        List<Long> childR = this.getIds(id,2);
        int number = 0;
        if(childL!=null) number = number+childL.size();
        if(childR!=null) number = number+childR.size();
        return number;
    }

    /**
     * 获取当前用户右社区算力总值
     */
    public BigDecimal userRight(Long id){
        try
        {
            String[] ssk=cesspitRecordService.getRightHashRate(id);
            if(ssk==null || ssk.length==0)
                return BigDecimal.ZERO;
            BigDecimal bgt= new BigDecimal(ssk[0]);
            return bgt;
        }catch (Exception e)
        {
            e.printStackTrace();
            log.info("====取右边出错=== e = {}",e.getMessage());
            return BigDecimal.ZERO;
        }
    }

    /**
     * 获取当前用户左社区算力总值
     */
    public BigDecimal userLeft(Long id){
        try
        {
            String[] ssk=cesspitRecordService.getLeftHashRate(id);
            if(ssk==null || ssk.length==0)
                return BigDecimal.ZERO;
            BigDecimal bgt= new BigDecimal(ssk[0]);
            return bgt;
        }catch (Exception e)
        {
            e.printStackTrace();
            log.info("====取右边出错=== e = {}",e.getMessage());
            return BigDecimal.ZERO;
        }

    }

    /**
     * 获取当前一个用户的小社区算力(左区算力和右区算力的小值，就是社区算力)
     * @param id
     * @return
     */
    public BigDecimal userCommun(Long id){
        BigDecimal left =   this.userLeft(id);
        BigDecimal right =   this.userRight(id);
        if(left==right) return left;
        return BigDecimalUtils.compare(left,right) ? right : left;
    }

    /**
     * 获取当前一个用户的社区算力加权值（小社区算力*矿机社区算力比例）
     * @param id
     * @return
     */
    public BigDecimal weighted(Long id){
        BigDecimal minSum = this.userCommun(id);
        BigDecimal userSum = BigDecimal.ZERO;
        if(minSum.compareTo(BigDecimal.ZERO)==0) return userSum;
        CesspitRecord cess= cesspitRecordService.findByMemberIdAndStatus(id,1L);
        if(cess==null) return userSum;
        Cesspit cesspit = cesspitService.findById(cess.getCesspitId());
        userSum = BigDecimalUtils.mulRound(minSum,cesspit.getCommunity(),DEFAULT_DIV_SCALE);
        return userSum;
    }

    /**
     * 获取所有用户的社区算力加权值并累加
     * @return
     */
    public BigDecimal allWeighted(){
        try
        {
            String[] ssk=cesspitRecordService.getTotalHashRateP();
            if(ssk==null || ssk.length==0)
                return BigDecimal.ZERO;
            BigDecimal bgt= new BigDecimal(ssk[0]);
            return bgt;
        }catch (Exception e)
        {
            e.printStackTrace();
            log.info("====取右边出错=== e = {}",e.getMessage());
            return BigDecimal.ZERO;
        }
    }


    /**
     * 添加失败，删除节点
     * @param id
     */
    public void delete(long id) {
        relationDao.delete(id);
    }

    /**
     * 获取所有激活用户
     */
    public List<Relation> findAll(){
        return relationDao.findAll();
    }


    public List<Relation> findAllMinerUser(){

        return relationDao.findAllMinerUser();
    }
}
